package com.banggood.upms.service.impl;

import com.banggood.silk.web.api.exception.SkbException;
import com.banggood.upms.bean.po.TreePermission;
import com.banggood.upms.bean.vo.TreePermissionVo;
import com.banggood.upms.bean.vo.search.TreePermissionSearchCriteria;
import com.banggood.upms.dao.TreeDao;
import com.banggood.upms.dao.TreePermissionDao;
import com.banggood.upms.service.TreePermissionService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author XuChuangFeng
 */
@Service
@Transactional(rollbackFor = SkbException.class)
public class TreePermissionServiceImpl extends BaseServiceImpl<TreePermission, TreePermissionDao> implements TreePermissionService {

    protected final Log logger = LogFactory.getLog(getClass());

    @Override
    @Autowired
    public void setDao(TreePermissionDao dao) {
        super.dao = dao;
    }

    @Autowired
    private TreeDao treeDao;

    /**
     * 只获取当前树节点的映射，并不会递归获取子节点的权限映射
     * @param vo
     * @return
     */
    @Override
    public List<TreePermission> selectByTreeIdAndSystemId(TreePermissionSearchCriteria vo) {
        return dao.selectByCriteria(vo);
    }

    @Override
    public String adjustTreePerms(List<TreePermission> posForInsert, List<String> idsForRemove) {
        String brief = this.insertTreePerms(posForInsert);
        if(!CollectionUtils.isEmpty(idsForRemove)) {
            for(String id : idsForRemove) {
                dao.deleteByPrimaryKey(id);
                logger.debug("该树节点删除的权限主键" + id);
            }
        }
        StringBuffer buffer= new StringBuffer(brief);
        buffer.append("删除了").append(idsForRemove.size()).append("个节点映射。");
        return buffer.toString();
    }

    @Override
    public String insertTreePerms(List<TreePermission> posForInsert) {
        if(!CollectionUtils.isEmpty(posForInsert)) {
            for(TreePermission po : posForInsert) {
                dao.insert(po);
                logger.debug("该树节点新增的权限主键：" + po.getPermissionId());
            }
        }
        return new StringBuffer().append("本次操作为该用户新增了").append(posForInsert.size()).append("个节点配置。").toString();
    }

    @Override
    public String deleteAll(TreePermissionVo vo) {
        int count = dao.deleteAll(vo);
        StringBuffer buffer = new StringBuffer();
        buffer.append("本次一共删除了").append(count).append("个用户与节点配置。");
        return buffer.toString();
    }
}
